<?php
/**
 * Created by PhpStorm.
 * User: nightelf
 * Date: 2020/2/13
 * Time: 15:55
 */

namespace App\Http\Controllers\Setting;


use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Model\AdminRoleModel;
use App\Http\Model\ApprovalModel;
use App\Http\Model\ApprovalNodeModel;
use App\Http\Model\ApprovalNodeRoleModel;
use App\Http\Model\ApprovalProcessModel;
use App\Http\Model\AttendanceModel;
use App\Http\Model\EmployeeModel;
use App\Http\Model\GroupMembersModel;
use App\Http\Model\GroupModel;
use App\Http\Model\HandymanAccountsModel;
use App\Http\Model\LivingModel;
use App\Http\Model\LoanModel;
use App\Http\Model\ProfessionModel;
use App\Http\Model\ProjectAreaModel;
use App\Http\Model\ProjectModel;
use App\Http\Model\ProjectSectionModel;
use App\Http\Model\SupplierModel;
use App\Http\Model\SupplierOrdersInfoModel;
use App\Http\Model\SupplierOrdersModel;
use App\Http\Model\WarehouseLogInfoModel;
use App\Http\Model\WarehouseLogModel;
use App\Http\Model\WorkmanAccountsModel;
use App\Http\Model\WorkmanAssignmentModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class ApprovalController extends Controller
{
    //账目审批状态，0待审核，1审核中，2已通过，3未通过,0和3能进行编辑
    /**
     * @return \Illuminate\Http\Response
     */
    public function nodeLists()
    {
        $approvalNodeModel = new ApprovalNodeModel();
        $approvalNodeRoleModel = new ApprovalNodeRoleModel();
        $this->data = $approvalNodeModel->lists();
        foreach($this->data as $key => $l){
            $this->data[$key]->roleList = $approvalNodeRoleModel->getRole(['nodeId'=>$l->id]);
        }

        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function deleteNode(Request $request)
    {
        $rules = [
            'id' => 'required|integer',
        ];
        $message = [
            'id.required' => '获取流程节点失败',
            'id.integer' => '流程节点参数类型错误',
        ];
        $param = $request->only('id');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $approvalNodeModel = new ApprovalNodeModel();
            $approvalNodeModel->delete($param);
            $approvalNodeRoleModel = new ApprovalNodeRoleModel();
            $approvalNodeRoleModel->delete(['nodeId'=>$param['id']]);
        } else {
            throw new ApiException($validator->errors()->first(), 150101);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function addNode(Request $request)
    {
        $rules = [
            'process' => 'required|integer',
        ];
        $message = [
            'process.required' => '获取参数失败',
            'process.integer' => '参数类型错误',
        ];
        $param = $request->only( 'process');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $approvalNodeModel = new ApprovalNodeModel();
            $approvalNodeModel->insert($param);
        } else {
            throw new ApiException($validator->errors()->first(), 150201);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function addNodeRole(Request $request)
    {
        $rules = [
            'nodeId' => 'required|integer',
            'roleId' => 'required|integer',
            'workmanAssignment' => 'required|integer',
            'workmanAccounts' => 'required|integer',
            'handymanAccounts' => 'required|integer',
            'attendance' => 'required|integer',
            'loan' => 'required|integer',
            'living' => 'required|integer',
            'supplier' => 'required|integer',
        ];
        $message = [
            'nodeId.required' => '获取节点参数失败',
            'nodeId.integer' => '节点参数类型错误',
            'roleId.required' => '获取角色参数失败',
            'roleId.integer' => '角色参数类型错误',
        ];
        $param = $request->only('nodeId', 'roleId','workmanAssignment','workmanAccounts','handymanAccounts','attendance','loan','living','supplier');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $approvalNodeRoleModel = new ApprovalNodeRoleModel();
            $approvalNodeRoleModel->delete(['nodeId'=>$param['nodeId'],'roleId'=>$param['roleId']]);
            $approvalNodeRoleModel->insert($param);
        } else {
            throw new ApiException($validator->errors()->first(), 150201);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function deleteRole(Request $request)
    {
        $rules = [
            'nodeId' => 'required|integer',
            'roleId' => 'required|integer',
        ];
        $message = [
            'nodeId.required' => '获取节点参数失败',
            'nodeId.integer' => '节点参数类型错误',
            'roleId.required' => '获取角色参数失败',
            'roleId.integer' => '角色参数类型错误',
        ];
        $param = $request->only('nodeId', 'roleId');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $approvalNodeRoleModel = new ApprovalNodeRoleModel();
            $approvalNodeRoleModel->delete($param);
        } else {
            throw new ApiException($validator->errors()->first(), 150201);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function approvalData(Request $request)
    {
        $rules = [
            'approvalId' => 'required|integer',
        ];
        $message = [
            'approvalId.required' => '获取项目参数失败',
            'approvalId.integer' => '项目参数类型错误',
        ];
        $param = $request->only('approvalId');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $approvalModel = new ApprovalModel();
            $approvalProcessModel = new ApprovalProcessModel();
            $adminId = $request->session()->get('adminId');
            $info = $approvalModel->info(['id'=>$param['approvalId']]);
            $startTime = $info['startTime'];
            $endTime = $info['endTime'];

            $processList = $approvalProcessModel->lists(['approvalId'=>$info['id'],'process'=>$info['process']]);
            $adminRole = (new AdminRoleModel())->getAdminRole(['adminId'=>$adminId]);
            foreach ($processList as $p){
                if ($p->roleId == $adminRole['roleId']){
                    $approval = true;
                    $process = $p;
                }else{
                    $approval = false;
                }
            }
            $info['month'] = date('Y-m',strtotime($info['startTime']));

            if (!empty($process)){
                $info['result'] = json_decode($process->result,true);
                $info['processId'] = $process->id;
            }else{
                $info['result'] = [];
            }

            $this->data['info'] = $info;
            $professionModel = new ProfessionModel();
            $professionLists = $professionModel->lists();
//            if ($info['status'] == 2){
//                $status = [1,3];
//            }elseif ($info['status'] == 3){
//                $status = 2;
//            }elseif ($info['status'] == 0 ||$info['status'] == 1){
//                $status = 1;
//            }
            $status = [1,2,3];
            //施工产值数据
            //当月施工总产值
            $workmanAssignmentModel = new WorkmanAssignmentModel();
            $projectAreaModel = new ProjectAreaModel();
            $condition = [
                'projectId'=>$info['projectId'],
                'startTime'=>$startTime,
                'endTime'=>$endTime,
//                'status'=>$status,
            ];
            $assignment['total'] = $workmanAssignmentModel->getSum($condition);
            $areaLists = $projectAreaModel->selectLists(['projectId'=>$info['projectId']]);
            $assignment['area'] = [];
            foreach ($areaLists as $key => $p){
                $condition['areaId'] = $p->id;
                $sum = $workmanAssignmentModel->getSum($condition);
                if ($sum == 0){
                    continue;
                }
                $assignment['area'][] = ['id'=>$p->id,'name'=>$p->name,'sum'=>$sum];
            }
            unset($condition['areaId']);
            $this->data['workmanAssignment'] = $assignment;

            //施工分账数据
            $workmanAccountsModel = new WorkmanAccountsModel();
            $accounts['total'] = $workmanAccountsModel->getSum($condition);
            $groupModel = new GroupModel();
            $groupLists = $groupModel->lists(['projectId'=>$info['projectId']]);
            $accounts['group'] = [];
            foreach ($groupLists as $key => $g){
                $condition['groupId'] = $g->id;
                $sum = $workmanAccountsModel->getSum($condition);
                $accounts['group'][] = ['id'=>$g->id,'name'=>$g->name,'sum'=>$sum];
            }
            unset($condition['groupId']);
            $this->data['workmanAccount'] = $accounts;
            //杂工数据
            $handymanAccountsModel = new HandymanAccountsModel();
            $handymanAccount['total'] = $handymanAccountsModel->getSum($condition);
            $handymanAccount['area'] = [];
            foreach ($areaLists as $key => $p){
                $condition['areaId'] = $p->id;
                $sum = $handymanAccountsModel->getSum($condition);
                if ($sum == 0){
                    continue;
                }
                $handymanAccount['area'][] = ['id'=>$p->id,'name'=>$p->name,'sum'=>$sum];
            }
            unset($condition['areaId']);
            $this->data['handymanAccount'] = $handymanAccount;
            //考勤数据
            $attendanceModel = new AttendanceModel();
            $attendance['total'] = $attendanceModel->getSum($condition);
            $attendance['profession'] = [];
            foreach ($professionLists as $key => $p){
                $condition['professionId'] = $p->id;
                $sum = $attendanceModel->getSum($condition);
                if ($sum == 0){
                    continue;
                }
                $attendance['profession'][] = ['id'=>$p->id,'name'=>$p->name,'sum'=>$sum];
            }
            unset($condition['professionId']);
            $this->data['attendance'] = $attendance;
            //现金借支
            $loanModel = new LoanModel();
            $condition['status'] = 1;
            $loan['total'] = $loanModel->getSum($condition);
            $loan['profession'] = [];
            foreach ($professionLists as $key => $p){
                $condition['professionId'] = $p->id;
                $sum = $loanModel->getSum($condition);
                if ($sum == 0){
                    continue;
                }
                $loan['profession'][] = ['id'=>$p->id,'name'=>$p->name,'sum'=>$sum];
            }
            unset($condition['professionId']);
            $this->data['loan'] = $loan;
            //生活费
            $livingModel = new LivingModel();

            $condition['type'] = 1;
            $living['total_recharge'] = $livingModel->getSum($condition);
            $condition['type'] = 2;
            $living['total_refund'] = $livingModel->getSum($condition);
            $living['profession'] = [];
            foreach ($professionLists as $key => $p){
                $condition['professionId'] = $p->id;
                $condition['type'] = 1;
                $sum_recharge = $livingModel->getSum($condition);
                $condition['type'] = 2;
                $sum_refund = $livingModel->getSum($condition);
                if ($sum_recharge == 0 && $sum_refund == 0){
                    continue;
                }
                $living['profession'][] = ['id'=>$p->id,'name'=>$p->name,'sum_recharge'=>$sum_recharge,'sum_refund'=>$sum_refund];
            }
            unset($condition['professionId']);
            $this->data['living'] = $living;
            //供应商采购
            $supplierOrdersModel = new SupplierOrdersModel();
            $supplierModel = new SupplierModel();
            $supplier['total'] = $supplierOrdersModel->getSum($condition);
            $suppliers = $supplierModel->selectLists();
            $supplier['supplier'] = [];
            foreach ($suppliers as $key => $s){
                $condition['supplierId'] = $s->id;
                $sum = $supplierOrdersModel->getSum($condition);
                if ($sum == 0){
                    continue;
                }
                $supplier['supplier'][] = ['id'=>$s->id,'name'=>$s->name,'sum'=>$sum];
            }
            unset($condition['supplierId']);
            $this->data['supplier'] = $supplier;
            //个人领料
            $warehouseLogModel = new WarehouseLogModel();
            $condition['status'] = 1;
            $condition['type'] = WarehouseLogModel::CONSUME;
            $consume['total'] = $warehouseLogModel->getSum($condition);
            $consumeEmployee = $warehouseLogModel->getConsumeEmployee($condition);
            foreach ($consumeEmployee as $key => $g){
                $condition['sourceEmployeeId'] = $g->sourceEmployeeId;
                $sum = $warehouseLogModel->getSum($condition);
                $consume['employee'][] = ['id'=>$g->sourceEmployeeId,'name'=>$g->name,'sum'=>$sum];
            }
            unset($condition['sourceEmployeeId']);
            $this->data['consume'] = $consume;
            //班组领料
            $condition['type'] = WarehouseLogModel::GROUP_CONSUME;
            $groupConsume['total'] = $warehouseLogModel->getSum($condition);
            $groupLists = $groupModel->lists(['projectId'=>$info['projectId']]);
            foreach ($groupLists as $key => $g){
                $condition['sourceGroupId'] = $g->id;
                $sum = $warehouseLogModel->getSum($condition);
                $groupConsume['group'][] = ['id'=>$g->id,'name'=>$g->name,'sum'=>$sum];
            }
            unset($condition['sourceGroupId']);
            $this->data['groupConsume'] = $groupConsume;
        } else {
            throw new ApiException($validator->errors()->first(), 150301);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function processLists(Request $request){
        $rules = [
            'month' => 'required|date_format:Y-m',
        ];
        $message = [
            'month.required' => '获取月份失败',
            'month.date_format' => '月份格式不正确',
        ];
        $param = $request->only('month');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $approvalModel = new ApprovalModel();
            $approvalNodeModel = new ApprovalNodeModel();
            $approvalProcessModel = new ApprovalProcessModel();

            $lists = $approvalModel->lists($param);
            foreach ($lists as $k =>$l) {
                $processList = $approvalProcessModel->lists(['approvalId'=>$l->id,'process'=>$l->process]);
                $lists[$k]->processList = $processList;
                $node = $approvalNodeModel->info(['approvalId'=>1,'process'=>$l->process]);
                $lists[$k]->processName = $node['name'];
            }
            $countLists = $approvalModel->countLists($param);
            $this->data = $this->tableFormat($lists,$countLists);
        } else {
            throw new ApiException($validator->errors()->first(), 150401);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }


    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function approvalDataAssignment(Request $request){
        $rules = [
            'projectId' => 'required|integer',
            'areaId' => 'required|integer',
            'approvalId' => 'required|integer',
        ];
        $message = [
            'projectId.required' => '获取项目参数失败',
            'projectId.integer' => '项目参数类型错误',
            'areaId.required' => '获取施工区参数失败',
            'areaId.integer' => '施工区参数类型错误',
            'approvalId.required' => '获取审批参数失败',
            'approvalId.integer' => '审批参数类型错误',
        ];
        $param = $request->only('projectId','approvalId','areaId');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $projectSectionModel = new ProjectSectionModel();
            $professionModel = new ProfessionModel();
            $professionLists = $professionModel->lists();
            $workmanAssignmentModel = new WorkmanAssignmentModel();
            $approvalModel = new ApprovalModel();
            $approval = $approvalModel->info(['id'=>$param['approvalId']]);
            $startTime = $approval['startTime'];
            $endTime = $approval['endTime'];

            $sectionLists = $projectSectionModel->selectLists(['areaId'=>$param['areaId']]);
            foreach ($sectionLists as $key => $s) {
                $sum = $workmanAssignmentModel->getSum(['sectionId'=>$s->id,'startTime'=>$startTime,'endTime'=>$endTime]);
                if (empty($sum)){
                    unset($sectionLists[$key]);
                    continue;
                }
                $sectionLists[$key]->sum  = $sum;
                $profession = [];
                foreach ($professionLists as $k =>$p){
                    $sum = $workmanAssignmentModel->getSum(['sectionId'=>$s->id,'professionId'=>$p->id,'startTime'=>$startTime,'endTime'=>$endTime]);
                    if ($sum == 0)continue;
                    $p->sum = $sum;
                    $profession[] = $p;
                }
                $sectionLists[$key]->profession = $profession;
            }
            $sectionLists = array_merge($sectionLists);
            $this->data = $sectionLists;
        } else {
            throw new ApiException($validator->errors()->first(), 150501);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function approvalDataAssignmentInfo(Request $request){
        $rules = [
            'projectId' => 'required|integer',
            'sectionId' => 'required|integer',
            'professionId' => 'required|integer',
            'approvalId' => 'required|integer',
        ];
        $message = [
            'projectId.required' => '获取项目参数失败',
            'projectId.integer' => '项目参数类型错误',
            'sectionId.required' => '获取施工区参数失败',
            'sectionId.integer' => '施工区参数类型错误',
            'professionId.required' => '获取工种参数失败',
            'professionId.integer' => '工种参数类型错误',
            'approvalId.required' => '获取审批参数失败',
            'approvalId.integer' => '审批参数类型错误',
        ];
        $param = $request->only('projectId','sectionId','approvalId','professionId');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $workmanAssignmentModel = new WorkmanAssignmentModel();
            $workmanAccountsModel = new WorkmanAccountsModel();
            $approvalModel = new ApprovalModel();
            $approval = $approvalModel->info(['id'=>$param['approvalId']]);
            $startTime = $approval['startTime'];
            $endTime = $approval['endTime'];
            $groupModel = new GroupModel();
            $groupMembersModel = new GroupMembersModel();
//            $groupLists = $groupModel->lists(['projectId'=>$param['projectId'],'professionId'=>$param['professionId']]);

            $condition = [
                'projectId'=>$param['projectId'],
                'professionId'=>$param['professionId'],
                'sectionId'=>$param['sectionId'],
                'startTime'=>$startTime,
                'endTime'=>$endTime,
            ];
            $groupLists = $workmanAssignmentModel->getGroups($condition);
            foreach ($groupLists as $key => $g){
                $condition['groupId'] = $g->groupId;
                $groupLists[$key]->sum = $workmanAssignmentModel->getSum($condition);
                $assignment = $workmanAssignmentModel->lists($condition);
                if (empty($assignment)){
                    unset($groupLists[$key]);
                    continue;
                }
                $batch = $workmanAssignmentModel->getBatch($condition);
                $gms = $groupMembersModel->lists(['groupId' => $g->groupId]);
                foreach ($gms as $k => $gm) {
                    $condition['employeeId'] = $gm->employeeId;
                    $accounts = [];
                    for ($i = 1; $i <= $batch; $i++) {
                        $condition['batch'] = $i;
                        $account =  $workmanAccountsModel->info($condition);
                        if (!empty($account)){
                            $accounts[] = $account;
                        }else{
                            continue;
                        }
                    }
                    unset($condition['batch']);
                    $gm->accounts = $accounts;
                }
                unset($condition['employeeId']);
                $groupLists[$key]->assignment = $assignment;
                $groupLists[$key]->separate = $gms;
            }
            $this->data = array_values($groupLists);

        } else {
            throw new ApiException($validator->errors()->first(), 150601);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function approvalDataHandymanAccounts(Request $request){
        $rules = [
            'projectId' => 'required|integer',
            'areaId' => 'required|integer',
            'approvalId' => 'required|integer',
        ];
        $message = [
            'projectId.required' => '获取项目参数失败',
            'projectId.integer' => '项目参数类型错误',
            'areaId.required' => '获取施工区参数失败',
            'areaId.integer' => '施工区参数类型错误',
            'approvalId.required' => '获取审批参数失败',
            'approvalId.integer' => '审批参数类型错误',
        ];
        $param = $request->only('projectId','approvalId','areaId');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $projectSectionModel = new ProjectSectionModel();
            $professionModel = new ProfessionModel();
            $professionLists = $professionModel->lists();
            $handymanAccountsModel = new HandymanAccountsModel();
            $approvalModel = new ApprovalModel();
            $approval = $approvalModel->info(['id'=>$param['approvalId']]);
            $startTime = $approval['startTime'];
            $endTime = $approval['endTime'];

            $sectionLists = $projectSectionModel->selectLists(['areaId'=>$param['areaId']]);
            foreach ($sectionLists as $key => $s) {
                $sum = $handymanAccountsModel->getSum(['sectionId'=>$s->id,'startTime'=>$startTime,'endTime'=>$endTime]);
                if (empty($sum)){
                    unset($sectionLists[$key]);
                    continue;
                }
                $sectionLists[$key]->sum  = $sum;
                $profession = [];
                foreach ($professionLists as $k =>$p){
                    $sum = $handymanAccountsModel->getSum(['sectionId'=>$s->id,'professionId'=>$p->id,'startTime'=>$startTime,'endTime'=>$endTime]);
                    if ($sum == 0)continue;
                    $p->sum = $sum;
                    $profession[] = unserialize(serialize($p));
                }
                $sectionLists[$key]->profession = $profession;
            }
            $sectionLists = array_merge($sectionLists);
            $this->data = $sectionLists;
        } else {
            throw new ApiException($validator->errors()->first(), 150701);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function approvalDataHandymanAccountsInfo(Request $request){
        $rules = [
            'projectId' => 'required|integer',
            'sectionId' => 'required|integer',
            'professionId' => 'required|integer',
            'approvalId' => 'required|integer',
        ];
        $message = [
            'projectId.required' => '获取项目参数失败',
            'projectId.integer' => '项目参数类型错误',
            'sectionId.required' => '获取施工区参数失败',
            'sectionId.integer' => '施工区参数类型错误',
            'professionId.required' => '获取工种参数失败',
            'professionId.integer' => '工种参数类型错误',
            'approvalId.required' => '获取审批参数失败',
            'approvalId.integer' => '审批参数类型错误',
        ];
        $param = $request->only('projectId','sectionId','approvalId','professionId');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $handymanAccountsModel = new HandymanAccountsModel();
            $approvalModel = new ApprovalModel();
            $approval = $approvalModel->info(['id'=>$param['approvalId']]);
            $startTime = $approval['startTime'];
            $endTime = $approval['endTime'];
            $condition = [
                'projectId'=>$param['projectId'],
                'professionId'=>$param['professionId'],
                'sectionId'=>$param['sectionId'],
                'startTime'=>$startTime,
                'endTime'=>$endTime,
            ];
            $this->data = $handymanAccountsModel->lists($condition);
        } else {
            throw new ApiException($validator->errors()->first(), 150801);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     * @throws \Exception
     */
    public function approvalDataAttendance(Request $request){
        $rules = [
            'projectId' => 'required|integer',
            'professionId' => 'nullable|integer',
            'approvalId' => 'required|integer',
        ];
        $message = [
            'projectId.required' => '获取项目参数失败',
            'projectId.integer' => '项目参数类型错误',
            'professionId.integer' => '工种参数类型错误',
            'approvalId.required' => '获取审批参数失败',
            'approvalId.integer' => '审批参数类型错误',
        ];
        $param = $request->only(['projectId', 'approvalId', 'professionId']);
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $employeeModel = new EmployeeModel();
            $approvalModel = new ApprovalModel();
            $attendanceModel = new AttendanceModel();
            $approval = $approvalModel->info(['id'=>$param['approvalId']]);
            $startTime = $approval['startTime'];
            $endTime = $approval['endTime'];

            // 获取当前项目，考勤记录中的工人，并且去重
            $lists = DB::table('attendance')
                ->leftJoin('employee','employee.id','=','attendance.employeeId')
                ->where('attendance.projectId',$param['projectId'])
                ->where('employee.professionId',$param['professionId'])
                ->groupBy('attendance.employeeId')
                ->select('employeeId')
                ->get();
            foreach ($lists as $key => $l){
                $employeeInfo = $employeeModel->info(['id' => $l->employeeId]);
                foreach ($employeeInfo as $k => $info){
                    $lists[$key]->$k = $info;
                }
                $dayList = $employeeModel->datePeriod($startTime, $endTime, '1 day', 'j','attendance');
                $attendances = $attendanceModel->getLists(['employeeId'=>$l->id, 'startTime'=>$startTime, 'endTime'=>$endTime,'projectId'=>$param['projectId']]);
                //审批用的状态值
                if(empty($attendances)){
                    $status = 3;
                }else{
                    $status = 2;
                }
                if (!empty($attendances)){
                    foreach ($attendances as $a) {
                        $d = (new \DateTime($a->day))->format('j');
                        $dayList[$d]['long'] = empty($a->length)?'':$a->length;
                        $dayList[$d]['day'] = empty($a->day)?'':$a->day;
                        $dayList[$d]['projectName'] = empty($a->projectName)?'':$a->projectName;
                        $dayList[$d]['projectId'] = empty($a->projectId)?'':$a->projectId;
                        $dayList[$d]['isCurrent'] = $a->isCurrent;
                        $dayList[$d]['id'] = $a->id;
                        //审批用的状态值
                        $status = $a->status;
                    }
                    $lists[$key]->attendance = $dayList;
                    //审批用的状态值
                    $lists[$key]->attendanceStatus = $status;
                }else{
                    unset($lists[$key]);
                }
            }
            $this->data = [
                'startTime' => $startTime,
                'endTime' => $endTime,
                'data'=>array_values($lists->toArray()),
            ];
        } else {
            throw new ApiException($validator->errors()->first(), 410701);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     * @throws \Exception
     */
    public function approvalDataLoan(Request $request){
        $rules = [
            'projectId' => 'required|integer',
            'professionId' => 'nullable|integer',
            'approvalId' => 'required|integer',
        ];
        $message = [
            'projectId.required' => '获取项目参数失败',
            'projectId.integer' => '项目参数类型错误',
            'professionId.integer' => '工种参数类型错误',
            'approvalId.required' => '获取审批参数失败',
            'approvalId.integer' => '审批参数类型错误',
        ];
        $param = $request->only(['projectId', 'approvalId', 'professionId']);
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $approvalModel = new ApprovalModel();
            $approval = $approvalModel->info(['id'=>$param['approvalId']]);
            $param['startTime'] = $approval['startTime'];
            $param['endTime'] = $approval['endTime'];
            $loanModel = new LoanModel();
            $lists = $loanModel->lists($param);
            $countLists = $loanModel->countLists($param);
            $this->data = $this->tableFormat($lists, $countLists);
        } else {
            throw new ApiException($validator->errors()->first(), 410701);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     * @throws \Exception
     */
    public function approvalDataLiving(Request $request){
        $rules = [
            'projectId' => 'required|integer',
            'professionId' => 'nullable|integer',
            'approvalId' => 'required|integer',
        ];
        $message = [
            'projectId.required' => '获取项目参数失败',
            'projectId.integer' => '项目参数类型错误',
            'professionId.integer' => '工种参数类型错误',
            'approvalId.required' => '获取审批参数失败',
            'approvalId.integer' => '审批参数类型错误',
        ];
        $param = $request->only(['projectId', 'approvalId', 'professionId']);
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $approvalModel = new ApprovalModel();
            $approval = $approvalModel->info(['id'=>$param['approvalId']]);
            $param['startTime'] = $approval['startTime'];
            $param['endTime'] = $approval['endTime'];
            $livingModel = new LivingModel();
            $lists = $livingModel->lists($param);
            $countLists = $livingModel->countLists($param);
            $this->data = $this->tableFormat($lists, $countLists);
        } else {
            throw new ApiException($validator->errors()->first(), 410701);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     * @throws \Exception
     */
    public function approvalDataConsume(Request $request){
        $rules = [
            'projectId' => 'required|integer',
            'approvalId' => 'required|integer',
            'sourceEmployeeId' => 'required|integer',
        ];
        $message = [
            'projectId.required' => '获取项目参数失败',
            'projectId.integer' => '项目参数类型错误',
            'approvalId.required' => '获取审批参数失败',
            'approvalId.integer' => '审批参数类型错误',
            'sourceEmployeeId.required' => '获取参数失败',
            'sourceEmployeeId.integer' => '参数类型错误',
        ];
        $param = $request->only(['projectId', 'approvalId', 'sourceEmployeeId']);
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $approvalModel = new ApprovalModel();
            $approval = $approvalModel->info(['id'=>$param['approvalId']]);
            $param['startTime'] = $approval['startTime'];
            $param['endTime'] = $approval['endTime'];
            $warehouseLogInfoModel = new WarehouseLogInfoModel();
            $param['type'] = 4;
            $lists = $warehouseLogInfoModel->lists($param);
            $countLists = $warehouseLogInfoModel->countLists($param);
            $this->data = $this->tableFormat($lists, $countLists);
        } else {
            throw new ApiException($validator->errors()->first(), 410701);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     * @throws \Exception
     */
    public function approvalDataGroupConsume(Request $request){
        $rules = [
            'projectId' => 'required|integer',
            'sourceGroupId' => 'required|integer',
            'approvalId' => 'required|integer',
        ];
        $message = [
            'projectId.required' => '获取项目参数失败',
            'projectId.integer' => '项目参数类型错误',
            'sourceGroupId.required' => '获取班组参数失败',
            'sourceGroupId.integer' => '班组参数类型错误',
            'approvalId.required' => '获取审批参数失败',
            'approvalId.integer' => '审批参数类型错误',
        ];
        $param = $request->only(['projectId', 'approvalId', 'sourceGroupId']);
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $approvalModel = new ApprovalModel();
            $approval = $approvalModel->info(['id'=>$param['approvalId']]);
            $param['startTime'] = $approval['startTime'];
            $param['endTime'] = $approval['endTime'];
            $warehouseLogInfoModel = new WarehouseLogInfoModel();
            $param['type'] = 7;
            $lists = $warehouseLogInfoModel->lists($param);
            $countLists = $warehouseLogInfoModel->countLists($param);
            $this->data = $this->tableFormat($lists, $countLists);
        } else {
            throw new ApiException($validator->errors()->first(), 410701);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     * @throws \Exception
     */
    public function approvalDataSupplier(Request $request){
        $rules = [
            'projectId' => 'required|integer',
            'supplierId' => 'nullable|integer',
            'approvalId' => 'required|integer',
        ];
        $message = [
            'projectId.required' => '获取项目参数失败',
            'projectId.integer' => '项目参数类型错误',
            'supplierId.integer' => '工种参数类型错误',
            'approvalId.required' => '获取审批参数失败',
            'approvalId.integer' => '审批参数类型错误',
        ];
        $param = $request->only(['projectId', 'approvalId', 'supplierId']);
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $approvalModel = new ApprovalModel();
            $approval = $approvalModel->info(['id'=>$param['approvalId']]);
            $param['startTime'] = $approval['startTime'];
            $param['endTime'] = $approval['endTime'];
            $supplierOrdersModel = new SupplierOrdersModel();
            $lists = $supplierOrdersModel->lists($param);
            $supplierOrdersInfoModel = new SupplierOrdersInfoModel();
            foreach ($lists as $key => $list) {
                $infoLists = $supplierOrdersInfoModel->lists(['orderId'=>$list->id]);
                $lists[$key]->info = $infoLists;
            }
            $countLists = $supplierOrdersModel->countLists($param);
            $this->data = $this->tableFormat($lists, $countLists);
        } else {
            throw new ApiException($validator->errors()->first(), 410701);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function processInfo(Request $request){
        $rules = [
            'projectId' => 'required|integer',
            'month' => 'required|date_format:Y-m',
        ];
        $message = [
            'projectId.required' => '获取项目参数失败',
            'projectId.integer' => '项目参数类型错误',
            'month.date_format' => '月份格式不正确',
        ];
        $param = $request->only('projectId','month');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $approvalProcessModel = new ApprovalProcessModel();
            $adminId = $request->session()->get('adminId');
            $info = $approvalProcessModel->info(['projectId'=>$param['projectId'],'month'=>$param['month'],'adminId'=>$adminId]);
            if (empty($info)){
                throw new ApiException('没有权限查看审批数据', 150902);
            }else{
                $this->data = $info;
            }
        } else {
            throw new ApiException($validator->errors()->first(), 150901);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function projectProcessLists(Request $request){
        $rules = [
            'projectId' => 'required|integer',
            'month' => 'required|date_format:Y-m',
        ];
        $message = [
            'projectId.required' => '获取项目参数失败',
            'projectId.integer' => '项目参数类型错误',
            'month.required' => '获取月份失败',
            'month.date_format' => '月份格式不正确',
        ];
        $param = $request->only('month','projectId');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $approvalModel = new ApprovalModel();
            $approvalNodeModel = new ApprovalNodeModel();
            $approvalProcessModel = new ApprovalProcessModel();
            $list = $approvalModel->lists($param);
            foreach ($list as $k =>$l) {
                $processList = $approvalProcessModel->lists(['approvalId'=>$l->id,'process'=>$l->process]);
                $list[$k]->processList = $processList;
                $node = $approvalNodeModel->info(['approvalId'=>1,'process'=>$l->process]);
                $list[$k]->processName = $node['name'];
            }
            $countLists = $approvalModel->countLists($param);
            $this->data = $this->tableFormat($list,$countLists);
        } else {
            throw new ApiException($validator->errors()->first(), 151001);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function initiateApplication(Request $request){
        $rules = [
            'startTime' => 'required|date_format:Y-m-d',
            'endTime' => 'required|date_format:Y-m-d',
            'projectId' => 'required|integer'
        ];
        $message = [
            'startTime.required' => '获取审批起始时间失败',
            'startTime.date_format' => '审批起始时间格式不正确',
            'endTime.required' => '获取审批截止时间失败',
            'endTime.date_format' => '审批截止时间格式不正确',
            'projectId.required' => '获取项目参数失败',
            'projectId.integer' => '项目参数类型错误',
        ];
        $param = $request->only('startTime','endTime','projectId');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $approvalModel = new ApprovalModel();

            //批量循环在建项目列表
            $projectModel= new ProjectModel();
            $param['adminId'] = $request->session()->get('adminId');
            if ($param['projectId'] == 0){
                $projectLists = $projectModel->selectLists(['status'=>1]);
                foreach ($projectLists as $p){
                    //验证每个项目的账目审批时间是否和以前的账目审批时间有重合的地方
                    $result = $approvalModel->checkApproval(['projectId'=>$p->id,'startTime'=>$param['startTime']]);
                    if (!$result){
                        throw new ApiException($p->name.'项目本次审核周期和上次审核周期发生冲突', 151201);
                    }
                }
            }else{
                $info = $projectModel->info(['id'=>$param['projectId']]);
                $result = $approvalModel->checkApproval(['projectId'=>$info['id'],'startTime'=>$param['startTime']]);
                if (!$result){
                    throw new ApiException($info['name'].'本次审核周期和上次审核周期发生冲突', 151201);
                }
            }

            $approvalModel->initiateApplication($param);
        } else {
            throw new ApiException($validator->errors()->first(), 151101);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function accountSubmit(Request $request){
        $rules = [
            'projectId' => 'required|integer',
            'approvalId' => 'required|integer',
        ];
        $message = [
            'projectId.required' => '获取项目参数失败',
            'projectId.integer' => '项目参数类型错误',
            'approvalId.required' => '获取项目参数失败',
            'approvalId.integer' => '项目参数类型错误',
        ];
        $param = $request->only('projectId','approvalId');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $param['adminId'] = $request->session()->get('adminId');
            $approvalModel = new ApprovalModel();
            $result = $approvalModel->submission($param);
//            if (!$result){
//                throw new ApiException('保存失败', 151101);
//            }
        } else {
            throw new ApiException($validator->errors()->first(), 151101);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function submit(Request $request){
        $rules = [
            'approvalId' => 'required|integer',
        ];
        $message = [
            'approvalId.required' => '获取项目参数失败',
            'approvalId.integer' => '项目参数类型错误',
        ];
        $param = $request->only('approvalId');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $param['adminId'] = $request->session()->get('adminId');
            $approvalModel = new ApprovalModel();
            $approvalModel->submit($param);
        } else {
            throw new ApiException($validator->errors()->first(), 151101);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }
}